package com.nizi.wordoperate.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenerateWord {
//    public static void main(String[] args) throws Exception {
//        Map map = new HashMap();
//        map.put("name", "刁某某");
//        map.put("age", "24");
//        map.put("sex", "男");
//        map.put("id", "12121212121212");
//        CreatWordByModel("D:/三月.doc", map, "D:/downWord2.doc");
//    }

    public static void CreatWordByModel(String tmpFile, Map<String, String> contentMap, String exportFile) throws Exception {

        InputStream in = null;
        in = new FileInputStream(new File(tmpFile));

        HWPFDocument document = null;
        document = new HWPFDocument(in);
        // 读取文本内容
        Range bodyRange = document.getRange();

        // 替换内容
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
        }

//        InputStream is = new FileInputStream("D:\\table.docx");
//        XWPFDocument doc = new XWPFDocument(is);
//        List<XWPFParagraph> paras = doc.getParagraphs();
//
//
//        for (XWPFParagraph para : paras) {
//            //当前段落的属性
//            //CTPPr pr = para.getCTP().getPPr();
//            System.out.println(para.getText());
//        }


        //导出到文件
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write((OutputStream) byteArrayOutputStream);
            OutputStream outputStream = new FileOutputStream(exportFile);
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
